<template>
  <div class="container">
    <div class="main">
      <el-table :data="filteredTableData" border class="eltable">
        <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
        <el-table-column fixed prop="gd_state" label="工单状态" width="100">
          <template #default="{ row }">
            {{ dictionaryNames[row.gd_state] }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="gd_yxj" label="优先级" width="80">
          <template #default="{ row }">
            {{ dictionaryNames[row.gd_yxj] }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="gd_jd" label="工单进度" width="100">
          <template #default="{ row }">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${row.gd_jd}%` }">
                {{ row.gd_jd }}%
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gd_code" label="工单号" width="180"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码" width="180"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称" width="180"></el-table-column>
        <el-table-column prop="cp_xh" label="产品型号" width="180"></el-table-column>
        <el-table-column prop="ks_name" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="gd_jhsl" label="任务数量" width="180"></el-table-column>
        <el-table-column prop="gd_xqrq" label="交货日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gd_xqrq) }}
          </template>
        </el-table-column>
        <el-table-column prop="gd_jhkgsj" label="计划开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gd_jhkgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gd_jhwgsj" label="计划完成时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gd_jhwgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gd_bz" label="备注" width="180"></el-table-column>
        <el-table-column prop="create_by" label="创建人" width="180"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" @click="Details(row)">详情</el-button>
            <!-- <el-button type="text" @click="Split(row)">拆分</el-button> -->
            <el-button type="text" @click="openDialog(row)">派工</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <el-dialog title="生产工单派工" v-model="dialogVisible"
      style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <el-form-item label="工艺路线:" prop="gy_name">
          <el-input v-model="formData.gy_name" placeholder="请选择工艺路线" @click="toggleGYMTK"></el-input>
        </el-form-item>
        <el-form-item label="生产位置:" prop="cj_name">
          <el-input v-model="formData.gd_scwz" placeholder="请选择生产位置" @click="toggleDYMTK"></el-input>
        </el-form-item>
        <el-form-item label="生产班组:" prop="bz_name">
          <el-input v-model="formData.gd_scbz" placeholder="请选择生产班组" @click="toggleBZMTK"></el-input>
        </el-form-item>
        <div style="margin-top: 20px;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="生产工单详情" v-model="dialogVisibles" custom-class="plan-dialog"
      style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产工单号:">
              {{ formData.gd_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级:">
              {{ dictionaryNames[formData.gd_yxj] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编码:">
              {{ formData.cp_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称:">
              {{ formData.cp_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品分类:">
              {{ dictionaryNames[formData.cp_fl] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品型号:">
              {{ formData.cp_xh }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品品牌:">
              {{ formData.pp_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品类型:">
              {{ dictionaryNames[formData.cp_lx] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称:">
              {{ formData.ks_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编码:">
              {{ formData.ht_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务数量:">
              {{ formData.gd_jhsl }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交货时间:">
              {{ formatDate(formData.gd_xqrq) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划开始时间:">
              {{ formatDate(formData.gd_jhkgsj) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间:">
              {{ formatDate(formData.gd_jhwgsj) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产BOM:">
              {{ formData.bom_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单进度:">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: `${formData.gd_jd}%` }">
                  {{ formData.gd_jd }}%
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单状态:">
              {{ dictionaryNames[formData.gd_state] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:">
              {{ formData.gd_bz }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      ---------------------------------------------------------------------------------------------------------------------------------------------
      <p>生产资料:</p>
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane label="生成BOM" name="bom"></el-tab-pane>
        <el-tab-pane label="产品属性" name="attributes"></el-tab-pane>
        <el-tab-pane label="工艺文件" name="process"></el-tab-pane>
        <el-tab-pane label="产品文档" name="documents"></el-tab-pane>
        <el-tab-pane label="产品图片" name="images"></el-tab-pane>
      </el-tabs>

      <!-- 根据 activeTab 的值决定显示哪个表格 -->
      <el-table v-if="activeTab === 'bom'" :data="bomData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="wl_name" label="物料名称" />
        <el-table-column prop="wl_code" label="物料编码" width="150" />
        <el-table-column prop="wl_lx" label="物料类型" />
        <el-table-column prop="wl_xh" label="物料规格" />
        <el-table-column prop="dw_name" label="物料单位" />
        <el-table-column prop="wl_ly" label="物料来源" />
        <el-table-column prop="bomxq_sl" label="基本用料" width="80" />
      </el-table>

      <el-table v-if="activeTab === 'attributes'" :data="attributesData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attributeName" label="属性名称" />
        <el-table-column prop="attributeValue" label="属性值" width="200" />
        <!-- 其他列 -->
      </el-table>

      <!-- 可以继续添加其他选项卡对应的表格 -->
      <el-table v-if="activeTab === 'process'" :data="processData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="processName" label="工序名称" />
        <el-table-column prop="processDetail" label="工艺文件" width="200" />
        <!-- 其他列 -->
      </el-table>

      <el-table v-if="activeTab === 'documents'" :data="documentsData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="documentName" label="文档名称" />
        <el-table-column prop="uploadDate" label="文档列表" width="200" />
        <!-- 其他列 -->
      </el-table>

      <el-table v-if="activeTab === 'images'" :data="imagesData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="imageName" label="产品图片" />
        <el-table-column prop="imageUrl" label="图片列表" width="300" />
        <!-- 其他列 -->
      </el-table>

      <div style="margin-top: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveForm">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="isGYMTKVisible" title="选择工艺"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <GYMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection"></GYMTK>
    </el-dialog>

    <el-dialog v-model="isWZMTKVisible" title="生产位置"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <DYMTK @selection-confirmed="handleSelectionConfirmeds" @cancel-selection="handleCancelSelection"></DYMTK>
    </el-dialog>
    <el-dialog v-model="isBZMTKVisible" title="生产班组"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <BZMTK @selection-confirmed="handleSelectionConfirmedss" @cancel-selection="handleCancelSelection"></BZMTK>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, watchEffect, computed } from 'vue';
import { ElMessage } from 'element-plus';
import DYMTK from '../MTK/DYMTK.vue';
import BZMTK from '../MTK/BZMTK.vue';
import GYMTK from '../MTK/GYMTK.vue';

export default {
  components: { DYMTK, BZMTK, GYMTK },
  setup() {
    const searchKey = ref('');
    const tableData = ref([]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const dictionaryNames = ref({}); // 存储字典名称  
    const dialogVisible = ref(false);
    const dialogVisibles = ref(false);
    const dialogVisibless = ref(false);
    const formData = ref({
      cj_name: null,  // 或者使用空字符串 ''  
    });
    const activeTab = ref('bom');
    const isGYMTKVisible = ref(false);
    const isBZMTKVisible = ref(false);
    const isWZMTKVisible = ref(false);
    const Details = async (row) => {
      formData.value = { ...row };
      const response = await axios.get('/api/Mbd_BOMxq/GetBom?wl_code=' + row.cp_code);
      bomData.value = response.data;
      dialogVisibles.value = true;
    };
    const bomData = ref([]);
    const attributesData = ref([
      { id: 1, attributeName: '颜色', attributeValue: '黑色' },
      { id: 2, attributeName: '尺寸', attributeValue: '100x200' },
    ]);

    const processData = ref([
      { id: 1, processName: '切割', processDetail: '钢材切割' },
      { id: 2, processName: '焊接', processDetail: '钢材焊接' },
    ]);

    const documentsData = ref([
      { id: 1, documentName: '说明书', uploadDate: '2025-01-01' },
      { id: 2, documentName: '检测报告', uploadDate: '2025-02-01' },
    ]);

    const imagesData = ref([
      { id: 1, imageName: '产品图1', imageUrl: 'http://example.com/image1.jpg' },
      { id: 2, imageName: '产品图2', imageUrl: 'http://example.com/image2.jpg' },
    ]);
    const fetchData = async () => {
      try {
        const response = await axios.get('/api/Mes_SCGD/GetMes_SCGD');
        tableData.value = response.data;
        totalItems.value = response.data.length;
      } catch (error) {
        console.error('获取表格数据时出错:', error);
      }
    };

    const openDialog = (row) => {
      console.log(row.gd_state)
      if (row.gd_state == 58) {
        ElMessage.error('工单已投产不可操作');
        return;
      }
      // 如果 row 存在，将 row 的属性复制到 formData 中
      if (row) {
        formData.value = { ...row };
      }
      // 打开对话框
      dialogVisible.value = true;
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    const filteredTableData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      return tableData.value.slice(start, start + pageSize.value);
    });

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
    };

    const formatDictionaryName = async (dictionaryId) => {
      if (!dictionaryId) return '';
      if (dictionaryNames.value[dictionaryId]) {
        return dictionaryNames.value[dictionaryId];
      }
      try {
        const response = await axios.get(`/api/Dict/GetName?dictionary_id=${dictionaryId}`);
        dictionaryNames.value[dictionaryId] = response.data;
        return response.data;
      } catch (error) {
        console.error(`获取字典名称时出错: ${error.message}`);
        return '';
      }
    };
    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
      dialogVisibles.value = false;
      dialogVisibless.value = false;
      formData.value = {};
    };
    const handleCancelSelection = () => {
      isGYMTKVisible.value = false;
      isBZMTKVisible.value = false;
      isWZMTKVisible.value = false;
    }
    //显示工艺模态框
    const toggleGYMTK = () => {
      isGYMTKVisible.value = !isGYMTKVisible.value;
    };
    //
    const toggleDYMTK = () => {
      isWZMTKVisible.value = !isWZMTKVisible.value;
    };
    //选择客商
    const handleSelectionConfirmed = (data) => {
      formData.value.gy_code = data.id;
      formData.value.gy_name = data.name;
      console.log(formData.value.gy_name )
      isGYMTKVisible.value = false;
    };
    //显示班组模态框
    const toggleBZMTK = () => {
      isBZMTKVisible.value = !isBZMTKVisible.value;
    };
    //选择生产位置
    const handleSelectionConfirmeds = (data) => {
      formData.value.gd_scwz = data.name;
      isWZMTKVisible.value = false;
    };
    //选择生产班组
    const handleSelectionConfirmedss = (data) => {
      formData.value.gd_scbz = data.name;
      isBZMTKVisible.value = false;
    };
    // 监听表格数据变化，更新字典名称  
    watchEffect(() => {
      filteredTableData.value.forEach((row) => {
        if (row.gd_state) {
          formatDictionaryName(row.gd_state);
        }
        if (row.gd_yxj) {
          formatDictionaryName(row.gd_yxj);
        }
        if (row.cp_fl) {
          formatDictionaryName(row.cp_fl);
        }
        if (row.cp_lx) {
          formatDictionaryName(row.cp_lx);
        }
      });
    });
    const saveForm = () => {
      //进行工单任务的新增
      axios.post("/api/Mes_gdrw/AddMes_gdrw", {
        gdrw_state: 0,
        gdrw_yxj: formData.value.gd_yxj,
        gdrw_fzr: 0,
        gdrw_jd: formData.value.gd_jd,
        gdrw_code: generateGDRWCode(),
        gdrw_name: formData.value.gd_name,
        gdrw_scwz: formData.value.gd_scwz,
        gdrw_scbz: formData.value.gd_scbz,
        gy_code: formData.value.gy_code,
        gy_name: formData.value.gy_name,
        cp_code: formData.value.cp_code,
        cp_name: formData.value.cp_name,
        cp_xh: formData.value.cp_xh,
        cp_lx: formData.value.cp_lx,
        cp_fl: formData.value.cp_fl,
        pp_code: formData.value.pp_code,
        pp_name: formData.value.pp_name,
        dw_code: formData.value.dw_code,
        dw_name: formData.value.dw_name,
        ks_code: formData.value.ks_code,
        ks_name: formData.value.ks_name,
        ht_code: formData.value.ht_code,
        bom_code: formData.value.bom_code,
        gdrw_jhsl: formData.value.gd_jhsl,
        gdrw_xqrq: new Date(formData.value.gd_xqrq),
        gdrw_jhkgsj: new Date(formData.value.gd_jhkgsj),
        gdrw_jhwgsj: new Date(formData.value.gd_jhwgsj),
        gdrw_bz: formData.value.gd_bz,
        scgd_code: formData.value.gd_code,
        create_by: sessionStorage.getItem('u')
      }).then(response => {
        if (response.data) {
          //修改生产工单的状态为已投产
          axios.put(`/api/Mes_SCGD/UpdateStatus?scgd_code=${formData.value.gd_code}&state=58&update_by=${sessionStorage.getItem('u')}&scjh_code=1`)
          dialogVisible.value = false; // 关闭对话框
          fetchData();
          ElMessage.success('派工成功');
        }
      }).catch(error => {
        console.error('派工失败:', error);
      });
    }
    function generateGDRWCode() {
      const prefix = 'GDRW';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    fetchData();

    return {
      searchKey,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      openDialog,
      handleCurrentChange,
      formatDate,
      formatDictionaryName,
      dictionaryNames,
      filteredTableData,
      dialogVisible,
      Details,
      dialogVisibles,
      formData,
      activeTab,
      bomData,
      attributesData,
      processData,
      documentsData,
      imagesData,
      closeDialog,
      toggleGYMTK,
      toggleBZMTK,
      isGYMTKVisible,
      isBZMTKVisible,
      isWZMTKVisible,
      handleSelectionConfirmed,
      dialogVisibless,
      saveForm,
      generateGDRWCode,
      toggleDYMTK,
      handleSelectionConfirmeds,
      handleCancelSelection,
      handleSelectionConfirmedss
    };
  },
};  
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 98%;
  background-color: rgba(255, 255, 255, 0);
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 15px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #409eff;
  border-radius: 15px 0 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgb(0, 0, 0);
  font-weight: bold;
  transition: width 0.3s;
}

.custom-tabs .el-tabs__item {
  border-radius: 12px 12px 0 0;
}

.custom-tabs .el-tabs__item.is-active {
  background-color: #409eff;
  /* 活动选项卡的背景色 */
  color: white;
  /* 活动选项卡的字体颜色 */
}

.custom-tabs .el-tabs__item.is-inactive {
  background-color: #f5f7fa;
  /* 非活动选项卡的背景色 */
  color: #606266;
  /* 非活动选项卡的字体颜色 */
}

.custom-tabs .el-tabs__nav {
  margin-bottom: -1px;
  /* 使选项卡与下方内容相连 */
}

.el-table {
  margin-top: 20px;
}
</style>